using System;
using System.Collections.Generic;
using System.Linq;
using FireStarterModeller.BO;

namespace FireStarterModeller.Logic.Wizards
{
    /// <summary>
    /// Interface for implementing custom deletors for business objects.
    /// There are certain situations where the deleting of an object graph is complex
    /// and cannot be dealt with via the normal Prevent Delete, Cascade delete etc rules.
    /// This is an interface that allows you to specify the behaviour.
    /// </summary>
    public interface IDeleter
    {
        void MarkForDelete();
        void Delete();
    }

    public class DMSolutionDeleter : IDeleter
    {
        public IDMSolution DMSolution { get; private set; }

        public DMSolutionDeleter(IDMSolution dmSolution)
        {
            if (dmSolution == null) throw new ArgumentNullException("dmSolution");
            this.DMSolution = dmSolution;
        }

        public void Delete()
        {
            MarkForDelete();
            this.DMSolution.Save();
        }

        public void MarkForDelete()
        {
            foreach (var propertyType in this.DMSolution.PropertyTypes.ToArray())
            {
                propertyType.ForceDelete = true;
                propertyType.MarkForDelete();
                propertyType.ForceDelete = false;
            }
            var classDeleters = this.DMSolution.AllClasses
                .ToArray()
                .Select(dmClass => new DMClassDeleter(dmClass));
            foreach (var dmClassDeleter in classDeleters) { dmClassDeleter.DeleteAll();}

            this.DMSolution.MarkForDelete();
        }
    }
}